﻿#include "widget.h"
#include "ui_widget.h"
#include <QAxObject>
#include <QFileDialog>
#include <QStandardPaths>
#include <QDebug>
#include <QTextCodec>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
	int b;
    QAxObject *excel = new QAxObject(this);//建立excel操作对象
     excel->setControl("Excel.Application");//连接Excel控件
     excel->setProperty("Visible", false);//显示窗体看效果,选择ture将会看到excel表格被打开
     excel->setProperty("DisplayAlerts", true);//显示警告看效果
     QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿(excel文件)集合
     QString str = QFileDialog::getOpenFileName(this,"打开",
                                                     QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");
     workbooks->dynamicCall("Open(const QString&)", str);//打开刚才选定的excel
     QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
     QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",1);
     QAxObject *usedRange = worksheet->querySubObject("UsedRange");//获取表格中的数据范围

     QVariant var = usedRange->dynamicCall("Value");//将所有的数据读取刀QVariant容器中保存
     QList<QList<QVariant>> excel_list;//用于将QVariant转换为Qlist的二维数组
     QVariantList varRows=var.toList();
     if(varRows.isEmpty())
      {
          return;
      }
     const int row_count = varRows.size();
     QVariantList rowData;
     for(int i = 0; i < row_count; ++i)
     {
         rowData = varRows[i].toList();
         excel_list.push_back(rowData);
//         QString strCode = excel_list.at(i).at(0).toString();
//         QString strVar = excel_list.at(i).at(1).toString();
//         QString strPos = excel_list.at(i).at(2).toString();
//         QString strRow = excel_list.at(i).at(3).toInt();
//         qWarning() << QStringLiteral("编号") <<  strCode
//                    << QStringLiteral("变量") << strVar
//                    << QStringLiteral("位置") << strPos
//                    << QStringLiteral("行数") << strRow;
         qWarning() << QStringLiteral("编号") <<  excel_list.at(i).at(0).toString()
                    << QStringLiteral("变量") << excel_list.at(i).at(1).toString()
                    << QStringLiteral("位置") << excel_list.at(i).at(2).toString()
                    << QStringLiteral("行数") << excel_list.at(i).at(3).toInt();
        setReplaceContent(excel_list.at(i).at(1).toString(), excel_list.at(i).at(2).toString(),
                           excel_list.at(i).at(3).toInt());
     }//转换完毕
     for(int i = 0; i < m_VecCodec.size(); i++)
     {
         qWarning() << "vecCodec: " <<m_VecCodec.at(i);
     }
     qWarning() << "all finished...........";


     //然后将二维数组Qlist<Qlist<QVariant>>中的数据读取出来，到表格或者数据模型中，具体在这里过程省略

     workbook->dynamicCall( "Close(Boolean)", false );
     excel->dynamicCall( "Quit(void)" );
     delete excel;//因为前面选择了不显示excel窗口，如果这里不删除excel的话，excel依然是打开的，只是我们看不见（因为被隐藏起来了）
}

void Widget::setReplaceContent(const QString &strVar, const QString &strPos, int iRow)
{
    QString strAll;
    QStringList strList;
    QFile readFile(strPos);
    QFile writeFile;
    writeFile.setFileName(strPos);
    QString str;
    bool bUtf8 = true;

    if(!readFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qWarning() << "Can't open the file!";
    }
    else
    {
        QByteArray encodedStrRead = readFile.readAll();
//        QTextCodec *codecRead = QTextCodec::codecForName("GBK");
//        str = codecRead->toUnicode(encodedStrRead);

        QTextCodec::ConverterState state;
         QTextCodec *codec = QTextCodec::codecForName("UTF-8");
         str = codec->toUnicode(encodedStrRead.constData(), encodedStrRead.size(), &state);
         if (state.invalidChars > 0)
         {
             bUtf8 = false;
             str = QTextCodec::codecForName("GBK")->toUnicode(encodedStrRead);
         }
         else
         {
             bUtf8 = true;
             str = encodedStrRead;
         }

    }
    readFile.close();

    if(!writeFile.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qWarning()<< "Can't write the file!";
    }
    else
    {
        QTextCodec *codecWrite;
        if(bUtf8)
        {
            codecWrite = QTextCodec::codecForName("UTF-8");
        }
        else
        {
            codecWrite = QTextCodec::codecForName("GBK");
        }
        QByteArray encodedStrWrite = codecWrite->fromUnicode(str);
        writeFile.write(encodedStrWrite);
    }
    writeFile.close();

    QTextCodec* pTextCodec;
    if(!readFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qWarning() << "Can't open the file!";
    }
    else
    {      
        //测试
        QTextStream readStream(&readFile);
        pTextCodec = readStream.codec();
        QString strCodec = QString::fromLocal8Bit(pTextCodec->name());
        m_VecCodec.append(strCodec);

//        readStream.setCodec(pTextCodec);
//        readStream.setCodec("UTF-8");
        if(bUtf8)
        {
            readStream.setCodec("UTF-8");
        }
        else
        {
            readStream.setCodec("GBK");
        }
        strAll = readStream.readAll();
    }
    readFile.close();

    if(!writeFile.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qWarning()<< "Can't write the file!";
    }
    else
    {
        QTextStream writeStream(&writeFile);
//        writeStream.setCodec(pTextCodec);
//        writeStream.setCodec("UTF-8");
        if(bUtf8)
        {
            writeStream.setCodec("UTF-8");
        }
        else
        {
            writeStream.setCodec("GBK");
        }
        strList = strAll.split("\n");
        for(int i = 0; i < strList.count(); i++)
        {
//            QString strContent = writeStream.readLine(i);
            if(i == strList.count() - 1)
            {
                //最后一行不需要换行
                writeStream << strList.at(i);
            }
            else
            {
                QString strContain1 = " " + strVar + " ";
                QString strContain2 = " " + strVar + ",";
                QString strContain3 = " " + strVar + ")";
                QString strContain4 = "&" + strVar + " ";
                QString strContain5 = "&" + strVar + ",";
                QString strContain6 = "&" + strVar + ")";
                QString strContain7 = "*" + strVar + " ";
                QString strContain8 = "*" + strVar + ",";
                QString strContain9 = "*" + strVar + ")";

                QString strDefaultvalue1 = " " + strVar + "=";
                QString strDefaultvalue2 = " " + strVar + " " + "=";
                QString strDefaultvalue3 = "&" + strVar + "=";
                QString strDefaultvalue4 = "&" + strVar + " " + "=";
                QString strDefaultvalue5 = "*" + strVar + "=";
                QString strDefaultvalue6 = "*" + strVar + " " + "=";
                QVector <QString> vecDefaultvalue = {strDefaultvalue1, strDefaultvalue2,
                                                     strDefaultvalue3, strDefaultvalue4,
                                                     strDefaultvalue5, strDefaultvalue6};

                if(i == 0)
                {
                    QString strTxt = strList.at(0);
                }
                if(i + 1 == iRow)
                {
                    QString strContent = strList.at(iRow - 1);
                    bool bReplace = true;

                    //判断是未引用的形参有默认值则先不做替换
                    for(int i = 0; i < vecDefaultvalue.size(); i++)
                    {
                        if(strContent.contains(vecDefaultvalue.at(i)))
                        {
                            writeStream << strContent << '\n';
                            bReplace = false;
                        }
                    }

                    if(bReplace)
                    {
                        if(strContent.contains(strContain1))
                        {
                            strContent.replace(strContain1, "");
                        }
                        else if(strContent.contains(strContain2))
                        {
                            strContent.replace(strContain2, ",");
                        }
                        else if(strContent.contains(strContain3))
                        {
                            strContent.replace(strContain3, ")");
                        }
                        else if(strContent.contains(strContain4))
                        {
                            strContent.replace(strContain4, "&");
                        }
                        else if(strContent.contains(strContain5))
                        {
                            strContent.replace(strContain5, "&,");
                        }
                        else if(strContent.contains(strContain6))
                        {
                            strContent.replace(strContain6, "&)");
                        }
                        else if(strContent.contains(strContain7))
                        {
                            strContent.replace(strContain7, "*");
                        }
                        else if(strContent.contains(strContain8))
                        {
                            strContent.replace(strContain8, "*,");
                        }
                        else if(strContent.contains(strContain9))
                        {
                            strContent.replace(strContain9, "*)");
                        }
                        else
                        {
                        }
                        writeStream << strContent << '\n';
                    }
                }
                else
                {
                    writeStream << strList.at(i) << '\n';
                }
            }
        }
    }
    writeFile.close();
}

void Widget::copyFromVAT(const QString &strPos)
{
    QFileInfo fileInfo(strPos);
    QString strName = fileInfo.fileName();
    QString strDesDir = "C:\\Users\\dell\\Desktop\\ddd";
    QString strNewPath = strDesDir + QDir::separator() + strName;
    bool bSuccess = QFile::copy(strPos, strNewPath);
    if(!bSuccess)
    {
        m_bFromVATSuccess = false;
    }
    else
    {
        QFile::remove(strPos);
    }
}

void Widget::copyToVAT(const QString &strPos)
{
    QFileInfo fileInfo(strPos);
    QString strName = fileInfo.fileName();
    QString strDesDir = "C:\\Users\\dell\\Desktop\\ddd";
    QString strNewPath = strDesDir + QDir::separator() + strName;
    bool bSuccess = QFile::copy(strNewPath, strPos);
    if(!bSuccess)
    {
        m_bToVATSuccess = false;
    }
}

void Widget::on_copyFromBtn_clicked()
{
    QAxObject *excel = new QAxObject(this);//建立excel操作对象
     excel->setControl("Excel.Application");//连接Excel控件
     excel->setProperty("Visible", false);//显示窗体看效果,选择ture将会看到excel表格被打开
     excel->setProperty("DisplayAlerts", true);//显示警告看效果
     QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿(excel文件)集合
     QString str = QFileDialog::getOpenFileName(this,"打开",
                                                     QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");
     workbooks->dynamicCall("Open(const QString&)", str);//打开刚才选定的excel
     QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
     QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",1);
     QAxObject *usedRange = worksheet->querySubObject("UsedRange");//获取表格中的数据范围

     QVariant var = usedRange->dynamicCall("Value");//将所有的数据读取刀QVariant容器中保存
     QList<QList<QVariant>> excel_list;//用于将QVariant转换为Qlist的二维数组
     QVariantList varRows=var.toList();
     if(varRows.isEmpty())
      {
          return;
      }
     const int row_count = varRows.size();
     QVariantList rowData;
     for(int i = 0; i < row_count; ++i)
     {
         rowData = varRows[i].toList();
         excel_list.push_back(rowData);
         qWarning() << QStringLiteral("编号") <<  excel_list.at(i).at(0).toString()
                    << QStringLiteral("位置") << excel_list.at(i).at(1).toString();
        copyFromVAT(excel_list.at(i).at(1).toString());
     }//转换完毕
     qWarning() << "copyFromVAT finished...........";
     qWarning() << "bAllSuccess: " << m_bFromVATSuccess;


     //然后将二维数组Qlist<Qlist<QVariant>>中的数据读取出来，到表格或者数据模型中，具体在这里过程省略

     workbook->dynamicCall( "Close(Boolean)", false );
     excel->dynamicCall( "Quit(void)" );
     delete excel;//因为前面选择了不显示excel窗口，如果这里不删除excel的话，excel依然是打开的，只是我们看不见（因为被隐藏起来了）
}

void Widget::on_copyToBtn_clicked()
{
    QAxObject *excel = new QAxObject(this);//建立excel操作对象
     excel->setControl("Excel.Application");//连接Excel控件
     excel->setProperty("Visible", false);//显示窗体看效果,选择ture将会看到excel表格被打开
     excel->setProperty("DisplayAlerts", true);//显示警告看效果
     QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿(excel文件)集合
     QString str = QFileDialog::getOpenFileName(this,"打开",
                                                     QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),"Excel 文件(*.xls *.xlsx)");
     workbooks->dynamicCall("Open(const QString&)", str);//打开刚才选定的excel
     QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
     QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",1);
     QAxObject *usedRange = worksheet->querySubObject("UsedRange");//获取表格中的数据范围

     QVariant var = usedRange->dynamicCall("Value");//将所有的数据读取刀QVariant容器中保存
     QList<QList<QVariant>> excel_list;//用于将QVariant转换为Qlist的二维数组
     QVariantList varRows=var.toList();
     if(varRows.isEmpty())
      {
          return;
      }
     const int row_count = varRows.size();
     QVariantList rowData;
     for(int i = 0; i < row_count; ++i)
     {
         rowData = varRows[i].toList();
         excel_list.push_back(rowData);
         qWarning() << QStringLiteral("编号") <<  excel_list.at(i).at(0).toString()
                    << QStringLiteral("位置") << excel_list.at(i).at(1).toString();
        copyToVAT(excel_list.at(i).at(1).toString());
     }//转换完毕
     qWarning() << "copyToVAT finished...........";
     qWarning() << "bAllSuccess: " << m_bToVATSuccess;


     //然后将二维数组Qlist<Qlist<QVariant>>中的数据读取出来，到表格或者数据模型中，具体在这里过程省略

     workbook->dynamicCall( "Close(Boolean)", false );
     excel->dynamicCall( "Quit(void)" );
     delete excel;//因为前面选择了不显示excel窗口，如果这里不删除excel的话，excel依然是打开的，只是我们看不见（因为被隐藏起来了）
}
